//
//  MKUIElementViewSwitch.m
//  MKUI
//
//  Created by 苏尚进 on 2023/7/10.
//  Copyright © 2023 moon. All rights reserved.
//

#import "MKUIElementViewSwitch.h"

@implementation MKUIElementViewSwitch
- (id)initWithFrame:(CGRect)frame{
    if(self=[super initWithFrame:frame]){
        self.switchView = [[UISwitch alloc] init];
        [self.switchView addTarget:self action:@selector(__onSwitchChange:) forControlEvents:(UIControlEventValueChanged)];
        [self.contentView addSubview:self.switchView];
        [self.segLayoutConstraint addItem:self.switchView];
    }
    return self;
}
- (void)__onSwitchChange:(UISwitch *)switchView{
    _on = switchView.isOn;
    if(self.whenChange){
        self.whenChange(self, self.isOn);
    }
}
- (void)setOn:(BOOL)on{
    if(_on==on)return;
    _on = on;
    self.switchView.on = on;
}
@end

@implementation MKUIElementListViewCellSwitch
+ (Class)elementViewClass{
    return MKUIElementViewSwitch.class;
}
- (id)initWithFrame:(CGRect)frame{
    if(self=[super initWithFrame:frame]){
        self.enableSelection = NO;
    }
    return self;
}
@end

@implementation MKUIElementTableViewCellModelSwitch
- (BOOL)el_on{
    return [self mk_boolForKeyPath:@"el_on"];
}
- (void)setEl_on:(BOOL)el_on{
    self[@"el_on"] = @(el_on);
    self.el_elementView.on = el_on;
}
- (void (^)(MKUIElementTableViewCellModelSwitch * _Nonnull, BOOL))el_whenSwitchChange{
    return self[@"el_whenSwitchChange"];
}
- (void)setEl_whenSwitchChange:(void (^)(MKUIElementTableViewCellModelSwitch * _Nonnull, BOOL))el_whenSwitchChange{
    self[@"el_whenSwitchChange"] = [el_whenSwitchChange copy];
}
@end

@implementation MKUIElementTableViewCellSwitch

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if(self=[super initWithStyle:style reuseIdentifier:reuseIdentifier]){
        self.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return self;
}
+ (Class)elementViewClass{
    return [MKUIElementViewSwitch class];
}
- (void)customReloadCellModel{
    [super customReloadCellModel];
    MKUIElementTableViewCellModelSwitch *cm = self.cellModel;
    MKUIElementViewSwitch *elementView = self.elementView;
    elementView.on = cm.el_on;
    @MK_WEAKIFY(self);
    elementView.whenChange = ^(MKUIElementViewSwitch * _Nonnull el, BOOL on) {
        @MK_NORMALIZE(self);
        MKUIElementTableViewCellModelSwitch *cm = self.cellModel;
        cm.el_on = on;
        if(cm.el_whenSwitchChange){
            cm.el_whenSwitchChange(cm,on);
        }
    };
}
@end
